package dao;


import java.util.Date;
import java.util.List;


import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

import beans.User;

import beans.Comment;
import beans.News;
@Transactional
public class CommentDAO {

	private HibernateTemplate hibernateTemplate;
	public void setSessionFactory(SessionFactory sessionFactory){
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}
	
	public void saveComment(Comment comment){
		comment.setDate(new Date());
		this.hibernateTemplate.save(comment);
	}
	public List<Comment> GetAllComments(){
		return this.hibernateTemplate.loadAll(Comment.class);
	}
	
	public void deleteComment(Comment comment){
		hibernateTemplate.delete(comment);
	}
	
	public List<Comment> DisplayComments(){
		Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Comment> list;
		Query query = session.createQuery("from Comment order by date");
		list = (List<Comment>)query.list();
		for(Comment n : list){
	        Hibernate.initialize(n.getUser());
	        Hibernate.initialize(n.getNews());
			}
		return list;
		
	}
	public Comment GetCommentById(int id){
        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        Query query = session.createQuery("from Comment where id=:id").setInteger("id", id);
        Comment comment = (Comment)query.uniqueResult();
        Hibernate.initialize(comment.getUser());
        Hibernate.initialize(comment.getNews());
        return comment;
}

		public List<Comment> GetCommentsByNewsId(int id){
        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        Query query = session.createQuery("SELECT c FROM Comment as c JOIN c.news news WHERE news.id=:id ORDER BY c.date desc").setInteger("id", id);
        List<Comment> comments = query.list();
        for(Comment x : comments){
                Hibernate.initialize(x.getNews());
                Hibernate.initialize(x.getUser());
        }
        return comments;
}

		public List<Comment> GetCommentsByUsername(String username){
        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        Query query = session.createQuery("SELECT c FROM Comment as c JOIN c.user user WHERE user.username=:username ORDER BY c.date desc LIMIT 5").setString("username", username);
        List<Comment> comments = query.list();
        for(Comment x : comments){
                Hibernate.initialize(x.getNews());
                Hibernate.initialize(x.getUser());
        }
        return comments;
}

}
